<template>
  <div v-loading="loading" class="game_result">
    <!-- 发布公告 -->
    <el-row :gutter="10">
      <el-col :span="8">
        <el-form ref="form" :model="noticeDto" label-width="80px">
          <el-form-item label="发布公告">
            <el-input v-model="noticeDto.announcement" type="textarea" />
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="8">
        <el-button :loading="noticeLoading" style="margin-top: 24px;" type="primary" size="mini" @click="putNotice">发布公告</el-button>
      </el-col>
    </el-row>
    <!-- 报表下载 -->
    <div class="report_box">
      <!-- 导出 -->
      <el-row :gutter="20" class="gl_my_15">
        <el-col><h3 class="gl_my_5">报表</h3></el-col>
      </el-row>
      <el-row :gutter="20" class="gl_my_15">
        <el-col>
          <span style="font-size: 14px;">按项目级别选择：</span>
          <el-select v-model="eventValue.CategoryId" style="width: 150px" size="mini" filterable clearable placeholder="请选择项目" @change="changeCategory" @clear="handleClear('category')">
            <el-option v-for="item in categoryData" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
          <el-select v-model="eventValue.GroupId" class="gl_ml_10" style="width: 120px" size="mini" filterable clearable placeholder="请选择组别" @change="changeGroup" @clear="handleClear('group')" @focus="judge('category')">
            <el-option v-for="item in groupData" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
          <el-select v-model="eventValue.Gender" class="gl_ml_10" style="width: 120px" size="mini" filterable clearable placeholder="请选择性别" @change="changeGender" @clear="handleClear('gender')" @focus="judge('group')">
            <el-option v-for="item in gender" :key="item.code" :label="item.value" :value="item.code" />
          </el-select>
          <el-select v-model="eventValue.EventId" class="gl_mx_10" style="width: 120px" size="mini" filterable clearable placeholder="请选择级别" @focus="judge('gender')">
            <el-option v-for="item in eventData" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
          <el-button type="warning" size="mini" :loading="downloadBracketLoading" @click="downloadBracket('Bracket')">按级别生成对阵表（带场次）</el-button>
        </el-col>
      </el-row>
      <el-row :gutter="20" class="gl_my_15">
        <el-col>
          <span style="font-size: 14px;">按赛事日期及赛制选择：</span>
          <el-select v-model="orderDayId" class="gl_ml_10" style="width: 150px" size="mini" filterable placeholder="请选择赛事日期">
            <el-option value="" label="全部" />
            <el-option v-for="item in gameDayList" :key="item.date" :value="item.date" :label="item.date && item.date.substring(0, 10)" />
          </el-select>
          <el-select v-model="typeId" class="gl_mx_10" style="width: 120px" size="mini" filterable placeholder="请选择赛制">
            <el-option value="" label="全部" />
            <el-option v-for="item in dict.eventFormat" :key="item.code" :label="item.value" :value="item.code" />
          </el-select>
          <el-button type="primary" size="mini" :loading="downloadStartListLoading" @click="downloadStartList('SessionSchedule')">生成场次表（秩序单）</el-button>
          <el-button type="primary" size="mini" :loading="downloadListLoading" @click="downloadStartListexc('SessionSchedule')">生成场次excel表（秩序单）</el-button>
        </el-col>
      </el-row>
      <el-row :gutter="20" class="gl_my_15">
        <el-col>
          <span style="font-size: 14px;">按赛事日期选择：</span>
          <el-select v-model="resultDayId" class="gl_mx_10" style="width: 150px" size="mini" filterable clearable placeholder="请选择赛事日期">
            <el-option v-for="item in gameDayList" :key="item.date" :value="item.date" :label="item.date && item.date.substring(0, 10)" />
          </el-select>
          <el-button type="success" size="mini" :loading="downloadloading" @click="downloadComRecord('ContestResults')">生成比赛记录单</el-button>
        </el-col>
      </el-row>
    </div>
    <!-- 比赛时间设置 -->
    <div class="report_box gl_mt_15">
      <div v-if="durations.length > 0">
        <h4>比赛时间设置：</h4>
        <div v-for="(item, index) in durations" :key="item.id" style="width: 350px" class="gl_dis_ib gl_fs_14">
          <div class="gl_pr_5 name">
            <el-popover placement="bottom" width="300" trigger="hover" :content="item.category.name">
              <span slot="reference" class="gl_ellipsis">{{ item.category.name }}：</span>
            </el-popover>
          </div>
          <el-form :ref="`ref${index}`" class="gl_dis_ib gl_middle" :inline="true" :model="createTimeInput">
            <el-form-item size="mini" :prop="`${index}.unitMinutes`" :rules="rules.unitMinutes">
              <el-input v-model="createTimeInput[index].unitMinutes" style="width: 80px" clearable />
              <span> 分</span>
            </el-form-item>
            <el-form-item size="mini" :prop="`${index}.unitSeconds`" :rules="rules.unitSeconds">
              <el-input v-model="createTimeInput[index].unitSeconds" style="width: 80px" clearable />
              <span> 秒</span>
            </el-form-item>
          </el-form>
        </div>
        <div class="gl_mb_15">
          <el-button :loading="timeLoading" style="width: 120px" type="primary" size="mini" @click="onRelease">确定</el-button>
        </div>
      </div>
      <el-row class="gl_my_15">
        计时计分数据接口地址：<span id="Address" class="gl_pr_10">{{ interfaceAddress }}</span><el-button type="text" @click="copyText('Address')">复制</el-button>
      </el-row>
    </div>
    <!-- 查询 -->
    <div class="demo-input-suffix gl_searchBox gl_mt_20">
      <el-row :gutter="20">
        <el-col :span="6" :lg="4">
          <p>赛事日期</p>
          <el-select v-model="api_GET_GameResultQO.StartDate" size="mini" placeholder="请选择赛事日期" filterable @change="changeGameDate()">
            <el-option v-for="item in gameDayList" :key="item.date" :value="item.date" :label="item.date && item.date.substring(0, 10)" />
          </el-select>
        </el-col>
        <el-col :span="6" :lg="4">
          <p>场地选择</p>
          <el-select v-model="api_GET_GameResultQO.LocationCode" size="mini" placeholder="请选择场地" filterable @change="changeLocation()">
            <el-option v-for="item in gameLocationList" :key="item.code" :value="item.code" :label="item.name" />
          </el-select>
        </el-col>
        <el-col :span="6" :lg="4">
          <p>单元选择</p>
          <el-select v-model="api_GET_GameResultQO.SessionId" size="mini" placeholder="请选择单元" filterable @change="getGameResultList()">
            <el-option v-for="item in gameSessionList" :key="item.id" :value="item.id" :label="handleShowSessionDate(item)" />
          </el-select>
        </el-col>
        <el-col :span="6" :lg="4">
          <p>赛事状态</p>
          <el-select v-model="api_GET_GameResultQO.StatusCode" size="mini" placeholder="请选择赛事类型" filterable @change="getGameResultList()">
            <el-option value="" label="全部" />
            <template v-for="item in dict.status">
              <template v-if="item.code==='Running' || item.code==='Scheduled' || item.code==='UnOfficial'">
                <el-option :key="item.code" :value="item.code" :label="item.value" />
              </template>
            </template>
          </el-select>
        </el-col>
        <!-- <el-col :span="6" :lg="4">
          <p>赛事类型</p>
          <el-select v-model="gameType" size="mini" placeholder="请选择赛事类型" filterable @change="getGameResultList()">
            <el-option value="" label="全部" />
            <el-option value="Competitive" label="淘汰赛" />
            <el-option value="NoneCompetitive" label="打分赛" />
          </el-select>
        </el-col> -->
        <el-col :md="6" :lg="4">
          <p>姓名/机构名/项目名称</p>
          <el-input v-model="search" placeholder="请输入关键词进行查询" size="mini" clearable @change="getGameResultList()" />
        </el-col>
        <el-col :span="6" :lg="4" class="search_btn">
          <!-- 查询按钮 -->
          <el-button type="primary" size="mini" @click="getGameResultList()">{{ $t('button.query') }}</el-button>
        </el-col>
      </el-row>
    </div>
    <!-- 场地选择 -->
    <!-- <div class="location_box gl_mt_20">
      <span
        v-for="item in gameLocationList"
        :key="item.code"
        class="location_item"
        :class="{ active: api_GET_GameResultQO.LocationCode === item.code }"
        @click="changeLocation(item)"
      >
        {{ item.name }}
      </span>
    </div> -->
    <div class="gl_mt_15">
      <p class="number">总：{{ All }}，已结束：{{ UnOfficial }}，未开始：{{ Scheduled }}</p>
      <el-tabs v-if="competitiveTableData.length > 0 || noneCompetitiveTableData.length > 0" v-model="activeName" type="card">
        <el-tab-pane v-if="gameType !== 'NoneCompetitive' && competitiveTableData.length > 0" label="淘汰赛" name="1">
          <competitive :competitive-table-data="competitiveTableData" @refreshPage="getGameResultList()" />
        </el-tab-pane>
        <el-tab-pane v-if="gameType !== 'Competitive' && noneCompetitiveTableData.length > 0" label="打分赛" name="2">
          <noneCompetitive :none-competitive-table-data="noneCompetitiveTableData" @refreshPage="refreshPageNC()" />
        </el-tab-pane>
      </el-tabs>
      <div v-else class="gl_mt_15">
        <el-table size="mini" />
      </div>
    </div>
  </div>
</template>

<script>
import { api_GET_DownLoadFileAddHeader } from '@/extend/api/file';
import { errorText } from '@/lib';
import competitive from './competitive';
import noneCompetitive from './noneCompetitive';
import { mapState, mapActions } from 'vuex';
import defaultPersonImg from '@/assets/images/face_default.png';
import validator from '@/lib/validate/index.js';
import { Api_GET_GameResultQO } from '@/lib/form/events';
import { SiSTKWEventsManagementCompetitonAnnouncementDto } from '@/lib/form/game/swaggerForm';
import {
  api_GET_EventsManagementCompetitionDay,
  api_GET_EventsManagementCategory, // 获取比赛项目
  api_GET_EventsManagementCompetitionSession,
  api_GET_EventsManagementCompetitionLocation,
  api_GET_EventsManagementUnitResultCompetitiveList,
  api_GET_EventsManagementUnitResultNoneCompetitiveList,
  api_GET_EventsManagementUnitResultUnitStatusList,
  api_PUT_EventsManagementCompetitionSettingAnnouncement, // 设置赛事公告
  api_PUT_EventsManagementCategoryCategoryDuration, // 比赛时间设置
  api_GET_EventsManagementCategoryCategoryDurationCompetitionId // 获取时间设置
} from '@/extend/api/gameswaggerApi/app';
export default {
  name: 'GameResult',
  components: {
    competitive,
    noneCompetitive
  },
  data() {
    return {
      loading: false,
      activeName: '1',
      interfaceAddress: '',
      gameId: '',
      noticeLoading: false,
      noticeDto: new SiSTKWEventsManagementCompetitonAnnouncementDto(),
      createTimeInput: {},
      rules: {
        unitMinutes: [
          {
            validator(rule, value, callback) {
              callback(validator.checkNumber(value, '必须是整数'));
            },
            trigger: 'blur'
          }
        ],
        unitSeconds: [
          {
            validator(rule, value, callback) {
              callback(validator.checkSeconds(value, '0-59之间的整数'));
            },
            trigger: 'blur'
          }
        ]
      },
      timeLoading: false,
      durations: [],
      downloadBracketLoading: false,
      categoryData: [],
      groupData: [],
      gender: [],
      eventData: [],
      eventValue: { // 对阵表id
        CategoryId: '',
        GroupId: '',
        Gender: '',
        EventId: ''
      },
      downloadloading: false,
      resultDayId: '', // 赛事日期id(比赛记录单)
      downloadStartListLoading: false,
      downloadListLoading: false,
      orderDayId: '', // 赛事日期id(秩序单)
      typeId: '', // 赛制id
      defaultPersonImg: defaultPersonImg, // 默认图片
      search: '',
      api_GET_GameResultQO: new Api_GET_GameResultQO(),
      competitiveLoading: false,
      noneCompetitiveLoading: false,
      competitiveTableData: [],
      noneCompetitiveTableData: [],
      // 赛事日期
      gameDayList: [],
      // 赛事单元
      gameSessionList: [],
      // 比赛场地
      gameLocationList: [],
      // 赛事类型
      gameType: '', // 竞技类('Competitive') 、非竞技类('NoneCompetitive')、全部('')
      Scheduled: 0,
      UnOfficial: 0,
      All: 0
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict,
      tenantId: state => state.user.tenantId
    })
  },
  created() {
    this.gameId = this.$route.params.id;
    this.getDict();
    this.getEventList();
    this.getTimeSetting();
    Promise.all([this.getGameDayList(), this.getGameLocationList()]).then(() => {
      this.api_GET_GameResultQO.StartDate = this.gameDayList[0] && this.gameDayList[0].date || '';
      this.api_GET_GameResultQO.LocationCode = this.gameLocationList[0] && this.gameLocationList[0].code || '';
      this.getGameSessionList().then(() => {
        this.api_GET_GameResultQO.SessionId = this.gameSessionList[0] && this.gameSessionList[0].id || '';
        if (this.api_GET_GameResultQO.SessionId) {
          this.getGameResultList();
        }
      });
    });
    var tenant = this.tenantId ? this.tenantId : '';
    this.interfaceAddress = WEB_CONFIG.VUE_APP_SWAGGER_GAME_BASE + '/api/' + tenant + '_' + this.$route.params.id;
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict' }),
    // 获取赛事公告
    // getNotice() {
    //   var that = this;
    //   that.loading = true;
    //   api_GET_EventsManagementCompetitionSettingAnnouncementCompetitionId(that.gameId).then(res => {
    //     that.noticeDto.announcement = res.announcement;
    //     that.loading = false;
    //   }, (error) => {
    //     that.loading = false;
    //     that.$message({ type: 'error', message: '获取公告失败  ' + error.error.message });
    //   });
    // },
    // 发布公告
    putNotice() {
      if (this.noticeDto.announcement === '') {
        this.$message({ type: 'warning', message: '内容为空，不能发布公告，请填写内容后再发布！' });
        return;
      }
      this.noticeLoading = true;
      this.noticeDto.competitionId = this.gameId;
      api_PUT_EventsManagementCompetitionSettingAnnouncement(this.noticeDto).then(res => {
        this.noticeLoading = false;
        this.$message({ type: 'success', message: '公告发布成功！' });
        this.noticeDto = new SiSTKWEventsManagementCompetitonAnnouncementDto();
      }, (error) => {
        this.noticeLoading = false;
        this.$message({ type: 'error', message: error.error && error.error.message || '发布公告失败！' });
      });
    },
    // 获取成绩列表
    getGameResultList() {
      if (!this.api_GET_GameResultQO.SessionId) {
        this.competitiveTableData = [];
        this.noneCompetitiveTableData = [];
        this.$message({ type: 'warning', message: '单元选择不能为空！' });
        return;
      }
      this.loading = true;
      if (this.gameType !== 'NoneCompetitive') {
        this.activeName = '1';
        this.getResultWidthCompetitiveList();
      }
      if (this.gameType !== 'Competitive') {
        this.activeName = '2';
        this.getResultWidthNoneCompetitiveList();
      }
      this.getFieldNumber();
    },
    // 查询竞技类比赛成绩
    getResultWidthCompetitiveList() {
      var that = this;
      const param = {
        CompetitionId: that.gameId,
        SessionId: that.api_GET_GameResultQO.SessionId,
        StatusCode: that.api_GET_GameResultQO.StatusCode,
        Search: that.search
      };
      api_GET_EventsManagementUnitResultCompetitiveList(param).then(res => {
        let competitiveData = res.items || [];
        that.activeName = competitiveData.length > 0 ? '1' : '2';
        if (competitiveData.length > 0) {
          competitiveData = competitiveData.map(item => {
            if (item.memberNamesA) {
              let strA = '';
              for (let a = 0; a < item.memberNamesA.length; a++) {
                const atem = item.memberNamesA[a];
                strA = strA + atem;
                if (a !== item.memberNamesA.length - 1) {
                  strA = strA + '/' + ' ';
                }
              }
              item.memberNamesA = strA;
            }
            if (item.memberNamesB) {
              let strB = '';
              for (let b = 0; b < item.memberNamesB.length; b++) {
                const btem = item.memberNamesB[b];
                strB = strB + btem;
                if (b !== item.memberNamesB.length - 1) {
                  strB = strB + '/' + ' ';
                }
              }
              item.memberNamesB = strB;
            }
            return { ...item };
          });
        }
        that.competitiveTableData = competitiveData;
        that.loading = false;
        // this.total = res.totalCount;
        // this.competitiveTableData = this.competitiveTableData.filter(item => item.playerNameA && item.playerNameB);
      }, () => {
        that.loading = false;
        that.$message({ type: 'error', message: '获取成绩列表失败！' });
      });
    },
    // 查询非竞技类比赛成绩
    getResultWidthNoneCompetitiveList() {
      var that = this;
      const param = {
        CompetitionId: that.gameId,
        SessionId: that.api_GET_GameResultQO.SessionId,
        StatusCode: that.api_GET_GameResultQO.StatusCode,
        Search: that.search
      };
      api_GET_EventsManagementUnitResultNoneCompetitiveList(param).then(res => {
        let noneCompetitiveData = res.items || [];
        if (noneCompetitiveData.length > 0) {
          noneCompetitiveData = noneCompetitiveData.map(item => {
            for (let i = 0; i < item.unitResultList.length; i++) {
              const list = item.unitResultList[i];
              if (list.memberNames) {
                let str = '';
                for (let j = 0; j < list.memberNames.length; j++) {
                  const jtem = list.memberNames[j];
                  str = str + jtem;
                  if (j !== list.memberNames.length - 1) {
                    str = str + '/' + ' ';
                  }
                }
                list.memberNames = str;
              }
            }
            return { ...item, noMoveTop: false, noMoveBottom: false, isSameRankDualScore: false };
          });
          noneCompetitiveData[0].noMoveTop = true;
          noneCompetitiveData[noneCompetitiveData.length - 1].noMoveBottom = true;
        }
        that.noneCompetitiveTableData = that.handleunitResultList(noneCompetitiveData);
        that.loading = false;
        // that.total = res.totalCount;
      }, () => {
        that.loading = false;
        that.$message({ type: 'error', message: '获取成绩列表失败！' });
      });
    },
    refreshPageNC() {
      this.getResultWidthNoneCompetitiveList();
      this.getFieldNumber();
    },
    // 处理非竞技成绩
    handleunitResultList(tableData) {
      if (tableData.length > 0) {
        var arr = [];
        for (var i = 0; i < tableData.length; i++) {
          var item = tableData[i];
          if (item.unitResultList.length < 2) {
            var ktem0 = JSON.parse(JSON.stringify(item));
            ktem0.unitResultList = false;
            ktem0 = Object.assign(ktem0, item.unitResultList[0]);
            arr.push(ktem0);
          } else {
            var ktem1 = JSON.parse(JSON.stringify(item));
            ktem1.unitResultList = true;
            ktem1 = Object.assign(ktem1, item.unitResultList[0]);
            var ktem2 = JSON.parse(JSON.stringify(item));
            ktem2.unitResultList = true;
            ktem2 = Object.assign(ktem2, item.unitResultList[1]);
            if (ktem1.isSameRank === true || ktem2.isSameRank === true) {
              // 行高亮，兼容双人打分制
              ktem1.isSameRankDualScore = true;
              ktem2.isSameRankDualScore = true;
            }
            arr.push(ktem1);
            arr.push(ktem2);
          }
        }
        return arr;
      } else {
        return [];
      }
    },
    // 获取赛事场次数（总，已结束，未开始）
    getFieldNumber() {
      var that = this;
      that.loading = true;
      const param = {
        CompetitionId: that.gameId,
        SessionId: that.api_GET_GameResultQO.SessionId,
        StatusCode: that.api_GET_GameResultQO.StatusCode,
        Search: that.search,
        EventTypeCode: that.gameType
      };
      api_GET_EventsManagementUnitResultUnitStatusList(param).then(res => {
        const numbers = res || [];
        that.All = 0;
        that.UnOfficial = 0;
        that.Scheduled = 0;
        for (let i = 0; i < numbers.length; i++) {
          const item = numbers[i];
          if (item.code === 'All') {
            that.All = item.count;
          } else if (item.code === 'UnOfficial') {
            that.UnOfficial = item.count;
          } else if (item.code === 'Scheduled') {
            that.Scheduled = item.count;
          }
        }
        that.loading = false;
      }, () => {
        that.loading = false;
        that.$message({ type: 'error', message: '获取赛事场次失败！' });
      });
    },
    // 获取赛事日期列表
    getGameDayList() {
      return new Promise((resolve, reject) => {
        this.loading = true;
        api_GET_EventsManagementCompetitionDay({ competitionId: this.gameId }).then(res => {
          this.gameDayList = res.items || [];
          this.loading = false;
          resolve(res.items);
        }, error => {
          this.$message({ type: 'error', message: '获取赛事日期列表失败！' });
          this.loading = false;
          reject(error);
        });
      });
    },
    // 获取赛事单元列表 - 单元数据依赖场地和赛事日期
    getGameSessionList() {
      return new Promise((resolve, reject) => {
        this.loading = true;
        this.CompetitionSessionQO = {};
        this.CompetitionSessionQO.CompetitionId = this.gameId;
        this.CompetitionSessionQO.Day = this.api_GET_GameResultQO.StartDate;
        this.CompetitionSessionQO.LocationCode = this.api_GET_GameResultQO.LocationCode;
        api_GET_EventsManagementCompetitionSession(this.CompetitionSessionQO).then(res => {
          // const _item = this.formatSessionListByTime(res.items);
          this.gameSessionList = res.items;
          this.loading = false;
          resolve(res.items);
        }, error => {
          this.$message({ type: 'error', message: '获取赛事单元列表失败！' });
          this.loading = false;
          reject(error);
        });
      });
    },
    // 获取场地列表
    getGameLocationList() {
      return new Promise((resolve, reject) => {
        this.loading = true;
        api_GET_EventsManagementCompetitionLocation({ competitionId: this.gameId }).then(res => {
          this.gameLocationList = res.items || [];
          this.loading = false;
          resolve(res.items);
        }, error => {
          this.$message({ type: 'error', message: '获取场地列表失败！' });
          this.loading = false;
          reject(error);
        });
      });
    },
    // 改变赛事日期
    changeGameDate() {
      this.getGameSessionList().then(() => {
        this.api_GET_GameResultQO.SessionId = this.gameSessionList[0] && this.gameSessionList[0].id || '';
        this.getGameResultList();
        // if (this.api_GET_GameResultQO.SessionId) {
        //   this.getGameResultList();
        // } else {
        //   this.competitiveTableData = [];
        //   this.noneCompetitiveTableData = [];
        // }
      });
    },
    // 改变场地
    changeLocation() {
      // this.api_GET_GameResultQO.LocationCode = locationItem.code;
      this.getGameSessionList().then(() => {
        this.api_GET_GameResultQO.SessionId = this.gameSessionList[0] && this.gameSessionList[0].id || '';
        // if (this.api_GET_GameResultQO.SessionId) {
        this.getGameResultList();
        // }
      });
    },
    // 处理单元中日期的展示
    handleShowSessionDate(sessionItem) {
      const _startTime = sessionItem.startTime && sessionItem.startTime.substring(11, 16);
      const _endTime = sessionItem.endTime && sessionItem.endTime.substring(11, 16);
      return `${sessionItem.type}(${_startTime}-${_endTime})`;
    },
    // 获取静态图片地址
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    errorPhoto() {
      const img = event.srcElement;
      img.src = this.defaultPersonImg;
    },
    // 复制文本
    copyText(id) {
      let target = null;
      target = document.querySelector('#' + id);
      const block = document.createRange();
      block.selectNode(target);
      window.getSelection().removeAllRanges();
      window.getSelection().addRange(block);
      const copyResult = document.execCommand('copy');
      window.getSelection().removeAllRanges();
      if (copyResult) {
        this.$message({ type: 'success', message: '复制成功' });
      }
    },
    // 获取时间设置
    getTimeSetting() {
      var that = this;
      that.loading = true;
      api_GET_EventsManagementCategoryCategoryDurationCompetitionId(that.gameId).then(res => {
        that.durations = res.durations;
        that.durations.filter((item, index) => {
          let _time = {};
          _time = {
            id: '',
            unitMinutes: '',
            unitSeconds: ''
          };
          that.$set(that.createTimeInput, index, _time);
        });
        for (const j in that.createTimeInput) {
          that.$set(that.createTimeInput[j], 'id', that.durations[j].id);
          const unitMinutes = that.durations[j].unitMinutes !== null ? that.durations[j].unitMinutes : '';
          that.$set(that.createTimeInput[j], 'unitMinutes', unitMinutes);
          const unitSeconds = that.durations[j].unitSeconds !== null ? that.durations[j].unitSeconds : '';
          that.$set(that.createTimeInput[j], 'unitSeconds', unitSeconds);
        }
        that.loading = false;
      }, (error) => {
        that.loading = false;
        that.$message({ type: 'error', message: '获取时间设置失败 ' + error.error.message });
      });
    },
    // 比赛时间设置
    onRelease() {
      var that = this;
      that.timeLoading = true;
      const _refCategoryScore = that.durations.map((item, index) => {
        var _validate = null;
        that.$refs[`ref${index}`][0].validate(valid => {
          if (valid) {
            _validate = true;
          } else {
            _validate = false;
          }
        });
        return {
          validate: _validate
        };
      });
      const _form = JSON.parse(JSON.stringify(that.createTimeInput));
      if (_refCategoryScore.every((item) => { return item.validate === true; })) {
        const params = {
          competitionId: that.gameId,
          durations: []
        };
        for (const i in _form) {
          const aa = _form[i].unitMinutes === '' && _form[i].unitSeconds !== '';
          const bb = _form[i].unitMinutes !== '' && _form[i].unitSeconds === '';
          if (aa || bb) {
            _form[i].unitMinutes = _form[i].unitMinutes ? _form[i].unitMinutes : 0;
            _form[i].unitSeconds = _form[i].unitSeconds ? _form[i].unitSeconds : 0;
          }
          params.durations.push(_form[i]);
        }
        api_PUT_EventsManagementCategoryCategoryDuration(params).then(res => {
          that.timeLoading = false;
          that.getTimeSetting();
          that.$message({ type: 'success', message: '比赛时间设置成功！' });
        }, (error) => {
          that.timeLoading = false;
          that.$message({ type: 'error', message: error.error && error.error.message || '赛事时间设置失败！' });
        });
      } else {
        that.timeLoading = false;
      }
    },
    /* 报表下载相关 */
    // 获取项目列表
    getEventList() {
      const eventVO = {};
      eventVO.CompetitionId = this.gameId;
      eventVO.IncludeEventGroup = true;
      eventVO.IncludeEvent = true;
      eventVO.IncludeGender = true;
      eventVO.EventTypeCode = 'Competitive';
      api_GET_EventsManagementCategory(eventVO).then(res => {
        this.categoryData = res.items || [];
      }, (error) => {
        this.$message({ type: 'error', message: error.error && error.error.message || '获取项目列表失败！' });
      });
    },
    // 获取组别
    changeCategory(id) {
      this.eventValue.GroupId = '';
      const groupData = this.categoryData.filter((item) => {
        return item.id === id;
      });
      this.groupData = groupData[0] ? groupData[0].eventGroups : [];
      this.handleClear('group');
    },
    // 获取性别
    changeGroup(id) {
      var that = this;
      that.eventValue.Gender = '';
      if (id !== '') {
        const event = that.groupData.filter((item) => {
          return item.id === id;
        });
        const gender = event[0].events.map((item) => {
          var value = '';
          for (let j = 0; j < that.dict.gender.length; j++) {
            var jtem = that.dict.gender[j];
            if (item.genderCode === jtem.code) {
              value = jtem.code;
            }
          }
          return value;
        });
        const genderList = Array.from(new Set(gender)) || [];
        that.gender = genderList.map((item) => {
          var genderItem = '';
          for (let j = 0; j < that.dict.gender.length; j++) {
            var jtem = that.dict.gender[j];
            if (item === jtem.code) {
              genderItem = jtem;
            }
          }
          return genderItem;
        });
      }
      this.handleClear('gender');
    },
    // 获取级别
    changeGender(code) {
      var that = this;
      that.eventValue.EventId = '';
      if (that.eventValue.GroupId !== '') {
        const eventData = that.groupData.filter((item) => {
          return item.id === this.eventValue.GroupId;
        });
        const events = eventData[0].events.filter((item) => {
          item.name = item.name ? item.name : item.longName;
          return item.genderCode === code;
        });
        that.eventData = events;
      }
    },
    // 先选项目，再选组别
    judge(code) {
      if (this.eventValue.CategoryId === '') {
        this.$message({
          type: 'warning',
          message: '请先选择项目！'
        });
      } else if (code !== 'category' && this.eventValue.GroupId === '') {
        this.$message({
          type: 'warning',
          message: '请先选择组别！'
        });
      } else if (code !== 'group' && code !== 'category' && this.eventValue.Gender === '') {
        this.$message({
          type: 'warning',
          message: '请先选择性别！'
        });
      }
    },
    // 部分清空
    handleClear(code) {
      if (code === 'category') {
        this.eventValue = {
          CategoryId: '',
          GroupId: '',
          Gender: '',
          EventId: ''
        };
      } else if (code === 'group') {
        this.eventValue.GroupId = '';
        this.eventValue.Gender = '';
        this.eventValue.EventId = '';
      } else if (code === 'gender') {
        this.eventValue.Gender = '';
        this.eventValue.EventId = '';
      }
    },
    // 对阵表
    downloadBracket(reportName) {
      var that = this;
      if (this.eventValue.CategoryId === '') {
        this.$message({ type: 'warning', message: '请选择项目级别！' });
        return;
      }
      this.downloadBracketLoading = true;
      const tempUrl = `/api/app/events-management/report`;
      const fileName = '对阵表（带场次）' + '.pdf';
      api_GET_DownLoadFileAddHeader(tempUrl, fileName, { ReportName: reportName, Format: 'PDF', CategoryId: this.eventValue.CategoryId, EventGroupId: this.eventValue.GroupId, EventId: this.eventValue.EventId, GenderCode: this.eventValue.Gender, HasMatchCode: 1 }).then(res => {
        that.downloadBracketLoading = false;
      }).catch(error => {
        that.downloadBracketLoading = false;
        errorText(error).then(function(text) {
          that.$message({ type: 'error', message: text });
        });
      });
    },
    // 比赛记录单
    downloadComRecord(contestResults) {
      var that = this;
      if (this.resultDayId === '') {
        this.$message({ type: 'warning', message: '请选择赛事日期！' });
        return;
      }
      this.downloadloading = true;
      const dayId = this.resultDayId.substring(0, 10);
      const tempUrl = `/api/app/events-management/report`;
      const fileName = '比赛记录单' + '.pdf';
      api_GET_DownLoadFileAddHeader(tempUrl, fileName, { ReportName: contestResults, Format: 'PDF', CompetitionId: this.gameId, DayId: dayId }).then(res => {
        that.downloadloading = false;
      }).catch(error => {
        that.downloadloading = false;
        errorText(error).then(function(text) {
          that.$message({ type: 'error', message: text });
        });
      });
    },
    // 场次表 （秩序单）
    downloadStartListexc(reportName) {
      var that = this;
      // if (this.orderDayId === '' || this.typeId === '') {
      //   this.$message({ type: 'warning', message: '请选择赛事日期及赛制！' });
      //   return;
      // }
      this.downloadListLoading = true;
      const dayId = this.orderDayId.substring(0, 10);
      const tempUrl = `/api/excel`;
      const fileName = '场次表 （秩序单）' + '.xlsx';
      api_GET_DownLoadFileAddHeader(tempUrl, fileName, { ReportName: reportName, CompetitionId: this.gameId, DayId: dayId, EventFormatCode: this.typeId }).then(res => {
        that.downloadListLoading = false;
      }).catch(error => {
        that.downloadListLoading = false;
        errorText(error).then(function(text) {
          that.$message({ type: 'error', message: text });
        });
      });
    },
    downloadStartList(reportName) {
      var that = this;
      // if (this.orderDayId === '' || this.typeId === '') {
      //   this.$message({ type: 'warning', message: '请选择赛事日期及赛制！' });
      //   return;
      // }
      this.downloadStartListLoading = true;
      const dayId = this.orderDayId.substring(0, 10);
      const tempUrl = `/api/app/events-management/report`;
      const fileName = '场次表 （秩序单）' + '.pdf';
      api_GET_DownLoadFileAddHeader(tempUrl, fileName, { ReportName: reportName, Format: 'PDF', CompetitionId: this.gameId, DayId: dayId, EventFormatCode: this.typeId }).then(res => {
        that.downloadStartListLoading = false;
      }).catch(error => {
        that.downloadStartListLoading = false;
        errorText(error).then(function(text) {
          that.$message({ type: 'error', message: text });
        });
      });
    }
  }
};
</script>
<style scoped>
.game_result .report_box {
  border:1px solid #eee;
  padding: 0 15px;
}
.location_item {
  display: inline-block;
  width: 50px;
  height: 50px;
  text-align: center;
  line-height: 50px;
  margin-right: 10px;
  border: 1px solid #eee;
  cursor: pointer;
  box-sizing: border-box;
  transition: all 0.3s ease;
}
.location_item:hover,
.location_item.active {
  background:#1890ff;
  color: #fff;
}
.number {
  float: right;
  width:500px;
  text-align: right;
  font-size: 14px;
  color: #606266;
}
.name {
  width: 130px;
  padding-bottom: 6px;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  text-align: right;
  display: inline-block;
}
</style>
